package com.stylefeng.guns.modular.JobHandler;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.modular.small.util.ObjectToXml;
import com.stylefeng.guns.modular.small.util.ResponseResultDTO;
import com.stylefeng.guns.modular.system.dao.ConsumerOrderMapper;
import com.stylefeng.guns.modular.system.model.ConsumerOrder;
import com.stylefeng.guns.modular.system.service.IConsumerOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/***
 * 订单同步状态
 */
@Slf4j
@Component
public class SyncOrderStatusJob {

    @Resource
    private ConsumerOrderMapper consumerOrderMapper;

    @Autowired
    private IConsumerOrderService consumerOrderService;

    /**
     * <p>10秒同步订单状态</p>
     *
     * @return
     * @des 定时通过订单流水号查询订单支付状态。
     * @returnSuccess {
     * transaction_id = 4200000399201909242530659987
     * , nonce_str = 3 nS7NY1CygFBTtVG
     * , trade_state = SUCCESS
     * , bank_type = CFT
     * , openid = oHZqt5k32ZiUWZaCc5UBsHFspBgs
     * , sign = 4 AF3B260D7848229671865EA235656BF
     * , return_msg = OK
     * , fee_type = CNY
     * , mch_id = 1539993251
     * , cash_fee = 1
     * , out_trade_no = AM_201909242415483112520
     * , cash_fee_type = CNY
     * , appid = wx224e8b702efc0e2b
     * , total_fee = 1
     * , trade_state_desc = 支付成功
     * , trade_type = JSAPI
     * , result_code = SUCCESS
     * , attach = 测试支付回调返回
     * , 订单号: AM_201909242415483112520
     * , time_end = 20190924154839
     * , is_subscribe = Y
     * , return_code = SUCCESS
     * }
     */
    @Scheduled(fixedDelay = 100 * 1000)
    public void syncOrderStatus() throws Exception {
        log.info("定时通过订单流水号查询订单支付状态开始.........");
        EntityWrapper<ConsumerOrder> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("status", 0).isNull("payTime").lt("pullCount", "4");
        List<ConsumerOrder> list = consumerOrderMapper.selectList(entityWrapper);
        for (ConsumerOrder order : list) {
            ResponseResultDTO resultDTO = consumerOrderService.queryOrder(order.getOrderNo());
            if ("0000".equals(resultDTO.getStatus())) {
                Map resultMap = ObjectToXml.xmlToMap(resultDTO.getData().toString());
                log.info("返回结果为：{}", resultMap);
                if ("SUCCESS".equals(MapUtils.getString(resultMap, "return_code")) &&
                        "OK".equals(MapUtils.getString(resultMap, "return_msg"))) {
                    String payTime = MapUtils.getString(resultMap, "time_end");
                    String transactionId = MapUtils.getString(resultMap, "transaction_id");
                    order.setPullCount(order.getPullCount() + 1);
                    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                    Date date = StringUtils.isBlank(payTime)?null:format.parse(payTime);
                    order.setPayTime(date);
                    order.setTransactionId(transactionId);
                    order.setStatus("SUCCESS".equals(MapUtils.getString(resultMap, "trade_state"))?1:0);
                    order.setTradeState(MapUtils.getString(resultMap, "trade_state"));
                    order.setTradeStateDesc(MapUtils.getString(resultMap, "trade_state_desc"));
                    order.setOpenId(MapUtils.getString(resultMap, "openid"));
                    consumerOrderService.updateById(order);
                }
            } else {
                log.info("查询订单异常,订单号为:{}", order.getOrderNo());
            }
        }
        log.info("定时通过订单流水号查询订单支付状态结束.........");
    }
}
